<?php
namespace yan\soundcaptcha;
use Yii;
use yii\helpers\Html;
use yii\helpers\Url;
class CaptchaImg extends \yii\base\Widget{
	public $template = '<div class="captchablock"><div id="captcha_img">{image} </div>
	<div id="captcha_control">{audio} <div id="captcha_refresh">{refresh}</div></div> 
	</div>{note}';
	public $src;
	public $imageOptions;
	public $audioOptions;
	public $options;
	public $note;
	public $length = 4;

	public function init()
    {
        parent::init();
        if (!isset($this->imageOptions['id'])) {
            $this->imageOptions['id'] = 'captcha-image-'.$this->id;
        }
        if(!isset($this->audioOptions['class'])){
        	$this->audioOptions['class'] = 'captcha-audio';
        }
        $this->registerJs();
    }

	public function run(){
		$image = Html::img($this->src, $this->imageOptions);
		$note = Html::tag('p', $this->note, ['class'=>'captcha-remarks']);
		echo strtr($this->template, [
            '{note}' => $note,
            '{image}' => $image,
            '{audio}' => $this->audioHtml(),
            '{refresh}' => '<a id="btnRefresh"href="javascript:void(0);">'.(isset($this->audioOptions['refresh']['text']) ? $this->audioOptions['refresh']['text'] : Yii::t('app', 'Refresh')).'</a>',
        ]);
	}
	public function audioHtml(){
		$shtml = Html::beginTag('div', $this->audioOptions);
		$shtml .= Html::button(
					isset($this->audioOptions['button']['text']) ? $this->audioOptions['button']['text'] : Yii::t('app', 'Play'), 
					isset($this->audioOptions['button']['options']) ? $this->audioOptions['button']['options'] : ['class'=>'btn btn-play', 'id'=>'bt_play_captcha']
				);
		$shtml .= Html::endTag('div');
		return $shtml;
	}
	public function registerJs(){
		$button_id = isset($this->audioOptions['button']['options']['id']) ? $this->audioOptions['button']['options']['id'] : 'bt_play_captcha';
		$image_id = $this->imageOptions['id'];
		$shtml1 = '';
		$shtml2 = '';
		$shtml3 = '';
		for($i=1; $i<$this->length; $i++){
			$shtml1 .= 'var ch'.($i+1).';'."\n";
			$shtml2 .= 'clearTimeout(ch'.($i+1).');'."\n";
			$shtml3 .= 'ch'.($i+1).' = setTimeout(function(){ audio['.($i).'].play(); }, '.($i+1).'500);'."\n";
		}
		$this->view->registerJs('
			'.$shtml1.'
			function sound4(){
				'.$shtml2.'
				var audio = new Array();
				for(var i=0; i<'.$this->length.'; i++){
					audio[i] = document.createElement("audio");
					audio[i].setAttribute("src", "'.Url::to(['/site/sound']).'?v="+i);
					audio[i].loop = false;
				}
				/*audio[0].addEventListener("ended", function(){
					if(typeof(audio[1])!="undefined"){
						audio[1].play();
					}
				}, false);
				audio[1].addEventListener("ended", function(){
					if(typeof(audio[2])!="undefined"){
						audio[2].play();
					}
				}, false);
				audio[2].addEventListener("ended", function(){
					if(typeof(audio[3])!="undefined"){
						audio[3].play();
					}
				}, false);		
				*/		
				audio[0].play();
				'.$shtml3.'
			}
			$("#'.$button_id.'").on("click", function(){
				sound4();
			});
			//刷新验证码
			if(typeof(refreshCaptcha)=="undefined"){
				function refreshCaptcha(_captcha){
				    $.getJSON("'.Url::to(['/site/captcha', 'refresh'=>'true']).'",function(res){
				        var dataUrl = _captcha.attr("data-url");
				        if(!dataUrl){
				            dataUrl = _captcha.attr("src");
				            _captcha.attr("data-url",dataUrl);
				        }
				        _captcha.attr("src",dataUrl+"?rd="+Math.random());
				    });
				}
			}
			
			$("#'.$image_id.'").on("click", function(){
				refreshCaptcha($(this));
			});
			$("#btnRefresh").on("click", function(){
				refreshCaptcha($("#'.$image_id.'"));
			});
			', \yii\web\View::POS_END);
	}
}